

import $data from "xcore/data";
import { reactive, ref } from "vue";
import $cmpnt, { IPageCmpnt } from 'xcore/cmpnt';
import _ from "lodash";
import { IPageMeta } from "xcore/data/store/store";
const singlePages=["home"]


export function load() {
   // 加载配置
    $data.provider.meta.getMetaConf().then((res:any) => {
        $data.store.conf = _.merge($data.store.conf, res)
        document.documentElement.className = "theme-primary" 
    })
}


export function start(pageId:string,group:string):{pages:any,data:any,pageId:string }{
    let pages = reactive<any>([])
    let data = ref({})
    $data.provider.meta.getMetaPage(pageId).then((res:any) => {
        let page:IPageMeta|undefined = undefined
        if (res.content && res.content != "{}") {
            let pageCmpnt = JSON.parse(res.content) as IPageCmpnt
            $cmpnt.resetBind(pageCmpnt)
            page = $data.func.bindPage(pageCmpnt, data)
        }else{
            let cmpntGroups = $cmpnt.group(group)
            if(!cmpntGroups||cmpntGroups.length==0) throw new Error(`未找到${group}类型的组件`)
            let cmpnt=$cmpnt.find(cmpntGroups[0].ctl.name).clone() as IPageCmpnt
            page = $data.func.bindPage(cmpnt, data)
        }
        if(page && !singlePages.includes(pageId.toLowerCase())){
           $data.func.setPage(page)
        }
        pages.push(page)
        
        //根据配置启动自动保存功能
        if($data.store.conf.editable && $data.store.conf.autoSave)
            $data.provider.saver.watchPage(pageId,pages[0])
    })
    return {pages,data,pageId}
}

export default {
    start,
    load,
}
